<template>
  <div>
    <van-nav-bar class="head">
      <template #title>
        <h3 style="color: #fff; font-weight: 200">城市列表</h3>
      </template>
      <template #left>
        <van-icon name="arrow-left" color="#fff" @click="$router.go(-1)"/>
      </template>
    </van-nav-bar>
    <!-- 当前城市 -->
     <van-index-bar class="indexBar" :sticky="false" highlight-color="#AE853A">
      <van-index-anchor>
        <span class="indexWord">当前城市</span>
        <van-cell
          :title="$store.state.currentcity"
        />
      </van-index-anchor>
    </van-index-bar>
    <!-- 热门城市 -->
    <van-index-bar class="indexBar" :sticky="false" highlight-color="#AE853A">
      <van-index-anchor>
        <span class="indexWord">热门城市</span>
        <van-cell
          @click="chooseCity(citem.label)"
          v-for="(citem,cindex) in HotCityList"
          :key="cindex"
          :title="citem.label"
        />
      </van-index-anchor>
    </van-index-bar>
    <!-- A-Z城市列表 -->
   <van-index-bar class="indexBar" :sticky="false" highlight-color="#AE853A">
      <van-index-anchor v-for="(item,index) in list" :key="index" :index="item.initial">
        <span class="indexWord">{{item.initial}}</span>
        <van-cell
          @click="chooseCity(citem.label)"
          v-for="(citem,cindex) in item.clist"
          :key="cindex"
          :title="citem.label"
        />
      </van-index-anchor>
    </van-index-bar>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getCity, getHotCity } from '@/api/area'
export default {
  methods: {
    onClickLeft () {
      Toast('返回')
    },
    chooseCity (cname) {
      this.$store.commit('changeCName', cname)
      this.$router.go(-1)
    }
  },
  async created () {
    const { body } = await getCity()
    this.cityList = body
    this.list = []
    for (let i = 65; i <= 90; i++) {
      const num = String.fromCharCode(i)
      this.list.push(num)
    }
    this.list = this.list.map(item => {
      const clist = []
      this.cityList.forEach(i => {
        if (i.short[0].toUpperCase() === item) {
          clist.push(i)
        }
      })
      return {
        initial: item,
        clist
      }
    })
  },
  data () {
    return {
      cityList: [],
      list: [],
      HotCityList: []
    }
  },
  watch: {
    HotCityList: {
      immediate: true,
      async handler () {
        const { body } = await getHotCity()
        this.HotCityList = body
      }

    }
  }
}
</script>

<style scoped lang="less">
.head {
  background-color: #21b97a;
  #title {
    color: #fff;
  }
}
</style>
